<template>
  <div class="category">
    <div class="category-header">
      <h2>{{ currentCategory ? currentCategory.name : '商品分类' }}</h2>
    </div>
    
    <!-- 加载状态 -->
    <div v-if="loading" class="loading">
      <div class="loading-spinner"></div>
      <span>加载中...</span>
    </div>
    
    <!-- 分类列表 -->
    <div class="category-list" v-if="!currentCategory && !loading">
      <div 
        class="category-item" 
        v-for="(item, index) in categories" 
        :key="index"
        @click="goToCategoryProducts(item)"
      >
        <div class="category-icon">{{ item.icon }}</div>
        <span>{{ item.name }}</span>
      </div>
    </div>

    <!-- 分类产品 -->
    <div class="category-products" v-if="currentCategory && !loading">
      <div class="back-button" @click="goBack">
        ← 返回分类
      </div>
      
      <div class="products-grid">
        <div 
          class="product-item" 
          v-for="(product, index) in products" 
          :key="index"
          @click="goToProduct(product)"
        >
          <div class="product-image-placeholder">{{ product.name }}</div>
          <div class="product-info">
            <span class="product-name">{{ product.name }}</span>
            <span class="product-price">¥{{ product.price }}</span>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useCategoryStore } from '@/stores/category'
import { getProductsByCategory } from '@/api/product'

const router = useRouter()
const route = useRoute()
const categoryStore = useCategoryStore()

const currentCategory = ref(null)
const products = ref([])
const loading = ref(false)

const categories = ref([
  { id: 1, name: '手机数码', icon: '📱' },
  { id: 2, name: '服装鞋包', icon: '👕' },
  { id: 3, name: '家居用品', icon: '🏠' },
  { id: 4, name: '美妆护肤', icon: '💄' },
  { id: 5, name: '运动户外', icon: '⚽' },
  { id: 6, name: '图书音像', icon: '📚' },
  { id: 7, name: '食品生鲜', icon: '🍎' },
  { id: 8, name: '母婴用品', icon: '👶' }
])

onMounted(async () => {
  // 加载分类数据
  await loadCategories()
  
  // 检查是否有查询参数
  const categoryId = route.query.id
  const categoryName = route.query.name
  
  if (categoryId && categoryName) {
    // 显示特定分类的产品
    currentCategory.value = {
      id: categoryId,
      name: decodeURIComponent(categoryName as string)
    }
    await loadCategoryProducts(categoryId)
  }
})

const loadCategories = async () => {
  try {
    const result = await categoryStore.fetchCategories()
    if (result.success && result.categories) {
      // 将数据库分类转换为前端格式
      categories.value = result.categories.map((cat: any) => ({
        id: cat.id,
        name: cat.name,
        icon: getCategoryIcon(cat.name)
      }))
    }
  } catch (error) {
    console.error('加载分类失败:', error)
  }
}

const loadCategoryProducts = async (categoryId: any) => {
  try {
    loading.value = true
    const response = await getProductsByCategory(categoryId)
    if (response.data && response.data.content) {
      products.value = response.data.content.map((product: any) => ({
        id: product.id,
        name: product.name,
        price: product.price,
        description: product.description,
        image: product.mainImage
      }))
    } else {
      // 如果没有数据，使用模拟数据
      products.value = [
        { id: 101, name: '示例商品1', price: 999 },
        { id: 102, name: '示例商品2', price: 1999 },
        { id: 103, name: '示例商品3', price: 2999 }
      ]
    }
  } catch (error) {
    console.error('加载分类商品失败:', error)
    // 使用模拟数据
    products.value = [
      { id: 101, name: '示例商品1', price: 999 },
      { id: 102, name: '示例商品2', price: 1999 },
      { id: 103, name: '示例商品3', price: 2999 }
    ]
  } finally {
    loading.value = false
  }
}

// 根据分类名称获取图标
const getCategoryIcon = (name: string) => {
  const iconMap: { [key: string]: string } = {
    '手机数码': '📱',
    '服装鞋包': '👕',
    '家居用品': '🏠',
    '美妆护肤': '💄',
    '运动户外': '⚽',
    '图书音像': '📚',
    '食品生鲜': '🍎',
    '母婴用品': '👶'
  }
  return iconMap[name] || '📦'
}

const goToCategoryProducts = (category: any) => {
  // 使用更安全的路由跳转方式
  router.push({
    path: '/category',
    query: {
      id: category.id.toString(),
      name: encodeURIComponent(category.name)
    }
  })
}

const goToProduct = (product: any) => {
  router.push(`/product/${product.id}`)
}

const goBack = () => {
  router.push('/category')
}
</script>

<style scoped>
.category {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding: 20px;
}

.category-header {
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
}

.category-header h2 {
  font-size: 20px;
  color: #333;
  margin: 0;
}

.loading {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 200px;
  background-color: #fff;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 20px;
}

.loading-spinner {
  border: 4px solid #f3f3f3;
  border-top: 4px solid #3498db;
  border-radius: 50%;
  width: 40px;
  height: 40px;
  animation: spin 1s linear infinite;
  margin-bottom: 16px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.loading span {
  color: #666;
  font-size: 14px;
}

.category-list {
  display: flex;
  flex-wrap: wrap;
  background-color: #fff;
  border-radius: 8px;
  padding: 20px;
}

.category-item {
  width: 25%;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px 0;
  cursor: pointer;
  transition: transform 0.2s ease;
}

.category-item:hover {
  transform: translateY(-2px);
}

.category-icon {
  font-size: 32px;
  margin-bottom: 8px;
}

.category-item span {
  font-size: 14px;
  color: #333;
  text-align: center;
}

.back-button {
  background-color: #fff;
  padding: 12px 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  cursor: pointer;
  color: #007aff;
  font-size: 16px;
}

.products-grid {
  display: flex;
  flex-wrap: wrap;
  background-color: #fff;
  border-radius: 8px;
  padding: 20px;
}

.product-item {
  width: calc(50% - 10px);
  margin: 5px;
  background-color: #fff;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  cursor: pointer;
  transition: transform 0.2s ease;
}

.product-item:hover {
  transform: translateY(-2px);
}

.product-image-placeholder {
  width: 100%;
  height: 120px;
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 12px;
  font-weight: bold;
  text-align: center;
  padding: 10px;
}

.product-info {
  padding: 12px;
}

.product-name {
  font-size: 14px;
  color: #333;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  overflow: hidden;
}

.product-price {
  font-size: 16px;
  color: #ff3b30;
  font-weight: bold;
  margin-top: 8px;
}
</style> 